package com.gao.weblog.jwt.util;


import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;
import io.jsonwebtoken.security.SignatureException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.stereotype.Component;

import java.security.Key;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Base64;
import java.util.Date;

@Component
public class JwtTokenHelper implements InitializingBean {

    @Value("${jwt.issuer}")
    private String issuer;
    private Key key;
    private JwtParser jwtParser;

    @Value("${jwt.secret}")
    public void setBase64Key(String base64Key){
        key = Keys.hmacShaKeyFor(Base64.getDecoder().decode(base64Key));
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        jwtParser = Jwts.parserBuilder().requireIssuer(issuer)
                .setSigningKey(key).setAllowedClockSkewSeconds(10)
                .build();
    }

    @Value("${jwt.tokenExpireTime}")
    private Long tokenExpireTime;

    public String generateToken(String username){
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime expire = now.plusMinutes(tokenExpireTime);

        return Jwts.builder().setSubject(username)
                .setIssuer(issuer)
                .setIssuedAt(Date.from(now.atZone(ZoneId.systemDefault()).toInstant()))
                .setExpiration(Date.from(expire.atZone(ZoneId.systemDefault()).toInstant()))
                .signWith(key)
                .compact();
    }

    public Jws<Claims> parseToken(String token){
        try {
            return jwtParser.parseClaimsJws(token);
        }catch (SignatureException | MalformedJwtException | UnsupportedJwtException | IllegalArgumentException e) {
            throw new BadCredentialsException("Token 不可用", e);
        }catch (ExpiredJwtException e) {
            throw new BadCredentialsException("Token 失效", e);
        }
    }

    private static String generateBase64Key(){
        Key secertKey = Keys.secretKeyFor(SignatureAlgorithm.HS512);

        String base64Key = Base64.getEncoder().encodeToString(secertKey.getEncoded());

        return base64Key;
    }

    public void validateToken(String token){
        jwtParser.parseClaimsJws(token);
    }

    public String getUsernameByToken(String token){
        try{
            Claims claims = jwtParser.parseClaimsJws(token).getBody();
            String username = claims.getSubject();
            return username;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) {
        String key = generateBase64Key();
        System.out.println("key: "+ key);
    }
}
